var config = require("../../config.js")
var util = require("../../utils/MD5.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCamera: true,
    devicePosition: "back",
    light: true,
  },

  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'low',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          showCamera: false,
        });
      }
    })
  },

  reTake() {
    this.setData({
      showCamera: true
    })
  },

  changeDevicePosition() {
    this.data.devicePosition == "back" ? this.setData({ devicePosition: "front" }) : this.setData({ devicePosition: "back" })
  },

  surePhoto() {
    this.uploadImages();
  },

  cancelPhoto() {
    wx.navigateBack({
      delta: 1
    })
  },

  uploadImages() {
    wx.showLoading({
      title: '正在上传',
    })
    wx.uploadFile({
      url: config.requestUrl + "?bNo=1907",
      filePath: this.data.src,
      name: 'file',
      formData: {
        filepath: encodeURI(this.data.src)
      },
      success: res => {
        if (res.data) {
          var data = res.data.replace(/\(|\)/g, "");

          var data2 = JSON.parse(data);
          wx.setStorage({
            key: 'photo_src',
            data: data2.filepath,
          })
          this.cancelPhoto();
        } else {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        }
      },
      fail: msg => {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
})